package com.cincc.taofangwang.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.taofangwang.R;
import com.cincc.taofangwang.adapter.TaskNumberAdapter;
import com.cincc.taofangwang.common.MyUtils;
import com.cincc.taofangwang.common.OkHttpUtils;
import com.cincc.taofangwang.common.PhoneInfoUtils;
import com.cincc.taofangwang.constant.CallConstant;
import com.cincc.taofangwang.model.TaskNumberModel;
import com.cincc.taofangwang.widget.CustomDrawerPopupView;
import com.cincc.taofangwang.widget.CustomWarnPopup;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class HomeFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "HomeFragment";
    TextView infoTv;
    int statusBarHeight;
    private PhoneInfoUtils phoneInfoUtils;
    //当前手机的手机号

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        phoneInfoUtils = new PhoneInfoUtils(requireActivity());
        initView(view);
        return view;
    }

    SmartRefreshLayout refreshLayout;
    TaskNumberAdapter taskNumberAdapter;
    List<TaskNumberModel> list = new ArrayList<>();

    TextView sexEdit, taskNumberEdit, statusEdit, purposeEdit;
    EditText nameEdit, remarkEdit;
    RecyclerView recyclerView;
    RelativeLayout emptyLayout;
    ImageView warnImg;
    //每次加载数量
    int limit = 10;
    //加载位置
    int start = 0;
    //当前任务id
    String currentTaskId = "";
    TaskNumberModel currentModel = null;

    private void initView(View view) {
        Toolbar toolbar = view.findViewById(R.id.toolbar);
        statusBarHeight = ImmersionBar.getStatusBarHeight(this);
        AppBarLayout.LayoutParams lp = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
        lp.topMargin = statusBarHeight + 10;
        TextView title = view.findViewById(R.id.title_text);
        infoTv = view.findViewById(R.id.info_tv);
        title.setText("号码列表");

        LinearLayout layout = view.findViewById(R.id.task_ll);
        layout.setOnClickListener(this);
        layout.setVisibility(View.VISIBLE);
        ImageView quitImg = view.findViewById(R.id.quit_img);
        quitImg.setOnClickListener(this);

        warnImg = view.findViewById(R.id.warn_img);
        warnImg.setOnClickListener(v -> showWarn(warnImg));
        recyclerView = view.findViewById(R.id.recyclerView_task_number);
        recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
        emptyLayout = view.findViewById(R.id.empty_layout);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        taskNumberAdapter = new TaskNumberAdapter(requireActivity(), list);
        taskNumberAdapter.setCallBack(index -> {
            currentModel = list.get(index);
            showForm(list.get(index));
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> taskPhoneList(true));
        refreshLayout.setOnLoadMoreListener(refreshLayout -> taskPhoneList(false));

        recyclerView.setAdapter(taskNumberAdapter);

        getInfo();
        getTaskAndService();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.task_ll) {
            switchTask();
        } else if (v.getId() == R.id.quit_img) {
            quit();
        } else if (v.getId() == R.id.edit_sex) {
            showSex();
        } else if (v.getId() == R.id.edit_status) {
            showStatus();
        } else if (v.getId() == R.id.edit_purpose) {
            showPurpose();
        } else if (v.getId() == R.id.call_relayout) {
            call();
        } else if (v.getId() == R.id.save_relayout) {
            saveForm();
        }
    }

    private void call() {
        if (TextUtils.isEmpty(CallConstant.currentPhone) || (!TextUtils.isEmpty(CallConstant.currentPhone) && CallConstant.currentPhone.contains(CallConstant.NAME))) {
            getXPhone();
        } else {
            new XPopup.Builder(requireActivity()).asConfirm("提示", "当前手机号和坐席不一致，确定呼叫吗？", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    getXPhone();
                }
            }, () -> {

            }).show();
        }
    }

    private void quit() {
        new XPopup.Builder(getContext()).asConfirm("提示", "确定要退出登录吗？",
                        () -> {
                            Intent i = new Intent(requireActivity(), LoginActivity.class);
                            requireActivity().startActivity(i);
                            requireActivity().finish();
                        })
                .show();
    }

    BottomSheetDialog bottomSheetDialog;

    private void showForm(TaskNumberModel model) {
        bottomSheetDialog = new BottomSheetDialog(requireActivity(), R.style.BottomSheetDialog);
        View bottomView = LayoutInflater.from(requireContext()).inflate(R.layout.home_form_popup, null);
        initForm(bottomView, model);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.show();
    }

    private void closeForm() {
        if (bottomSheetDialog != null) {
            bottomSheetDialog.cancel();
        }
    }

    private void switchTask() {
        new XPopup.Builder(requireActivity()).popupPosition(PopupPosition.Left)
                .asCustom(new CustomDrawerPopupView(requireActivity(), this.statusBarHeight, taskId -> {
                    Log.e(TAG, "callback: " + taskId);
                    currentTaskId = taskId;
                    taskPhoneList(true);
                }))
                .show();
    }

    private void refreshUI(JSONArray array) {
        try {
            for (int i = 0; i < array.length(); i++) {
                TaskNumberModel model = new TaskNumberModel(
                        array.getJSONObject(i).getString("o_task_id"),
                        array.getJSONObject(i).getString("o_task_name"),
                        array.getJSONObject(i).getString("phone1"),
                        array.getJSONObject(i).getString("o_state"),
                        array.getJSONObject(i).getString("reserve"),
                        array.getJSONObject(i).getString("coutomer_iphone"),
                        array.getJSONObject(i).getString("batch_name"),
                        array.getJSONObject(i).getString("customer_id"),
                        array.getJSONObject(i).getString("cust_group_name"),
                        array.getJSONObject(i).getString("cust_group_id"),
                        array.getJSONObject(i).getString("cust_type")
                );
                list.add(model);
            }
            start = list.size();
            taskNumberAdapter.notifyDataSetChanged();
            recyclerView.setVisibility(list.size() > 0 ? View.VISIBLE : View.GONE);
            emptyLayout.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getTaskAndService() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", "Agent");
            jsonObject.put("limit", limit);
            jsonObject.put("start", start);
            jsonObject.put("act", "getTaskAndService");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            getTaskAndServiceRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getTaskAndServiceRequest(String data) {
        Log.e(TAG, "doRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        if (data1.length() > 0) {
                            currentTaskId = data1.getJSONObject(0).getString("p_task_id");
                            taskPhoneList(true);
                        }
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }


    private void saveForm() {
        try {
            String status = statusEdit.getText().toString();
            if (TextUtils.isEmpty(status)) {
                Toast.makeText(requireActivity(), "请选择数据准确性", Toast.LENGTH_SHORT).show();
            } else {
                JSONArray array = new JSONArray();
                JSONObject c = new JSONObject();
                c.put("cust_group_id", currentModel.custGroupID);
                c.put("cust_group_name", currentModel.custGroupName);
                c.put("order_id", MyUtils.getOrderId());
                c.put("phone_no", currentModel.taskNumber);
                c.put("task_id", currentModel.taskID);

                c.put("sv_name", nameEdit.getText().toString());//姓名
                c.put("text_z", remarkEdit.getText().toString());//备注
                c.put("xingbie", sexEdit.getText().toString().length() > 0 ? Arrays.asList(CallConstant.sexList).indexOf(sexEdit.getText().toString()) : "");//性别 男：0 女：1
                c.put("yixiang", purposeEdit.getText().toString().length() > 0 ? (Arrays.asList(CallConstant.purposeList).indexOf(purposeEdit.getText().toString()) + 1) + "" : "");//意向 +1
                c.put("zhunquexing", (Arrays.asList(CallConstant.statusList).indexOf(status) + 1) + "");//准确性+1
                c.put("batch_name", currentModel.batchName);//导入批次
                c.put("coutomer_iphone", currentModel.coutomerIPhone);//隐藏号码
                c.put("cust_type", currentModel.custType);//号码来源
                c.put("reserve", currentModel.reserve);//客户信息

                array.put(c);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", array);
                jsonObject.put("id", "Order");
                jsonObject.put("act", "save");
                jsonObject.put("time", MyUtils.getCurrentTime());
                jsonObject.put("token", CallConstant.TOKEN);
                saveFormRequest(jsonObject.toString());
            }
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void saveFormRequest(String data) {
        Log.e(TAG, "saveFormRequest: " + data);
        BasePopupView show = new XPopup.Builder(requireActivity()).asLoading().show();
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        taskPhoneList(true);
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    requireActivity().runOnUiThread(() -> {
                        show.dismiss();
                        closeForm();
                    });
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                    show.dismiss();
                });
            }
        });
    }

    private void getXPhone() {
        try {
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("vcc_id", CallConstant.VCCID);
            c.put("calling_number", CallConstant.NAME);
            c.put("called_number", currentModel.taskNumber);
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Task");
            jsonObject.put("act", "setXPhone");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            getXPhoneRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getXPhoneRequest(String data) {
        Log.e(TAG, "getXPhoneRequest: " + data);
        BasePopupView show = new XPopup.Builder(requireActivity()).asLoading().show();
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        String xPhone = data1.getJSONObject(0).getString("xphone");
                        updateStatus();
                        MyUtils.jumpDial(requireActivity(), xPhone);
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    requireActivity().runOnUiThread(show::dismiss);
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                    show.dismiss();
                });
            }
        });
    }


    private void updateStatus() {
        try {
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("customer_id", currentModel.customerId);
            c.put("o_state", 5);
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Customer");
            jsonObject.put("act", "save");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            updateStatusRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void updateStatusRequest(String data) {
        Log.e(TAG, "getXPhoneRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        Log.e(TAG, "onSuccessful: update success");
                        taskPhoneList(true);
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void taskPhoneList(boolean isRefresh) {
        try {
            if (isRefresh) {
                start = 0;
                list.clear();
            }
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("vcc_id", CallConstant.VCCID);
            c.put("task_id", currentTaskId);
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Task");
            jsonObject.put("limit", limit);
            jsonObject.put("start", start);
            jsonObject.put("act", "taskPhoneList");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            taskPhoneListRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void taskPhoneListRequest(String data) {
        Log.e(TAG, "taskPhoneListRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        requireActivity().runOnUiThread(() -> refreshUI(data1));
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void getInfo() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", "Agent");
            jsonObject.put("act", "getInfo");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            getInfoRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getInfoRequest(String data) {
        Log.e(TAG, "getInfoRequest doRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "getInfoRequest onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        String phone = jsonObject.getJSONArray("data").getJSONObject(0).getString("name");
                        String vccId = jsonObject.getJSONArray("data").getJSONObject(0).getString("vccId");
                        requireActivity().runOnUiThread(() -> {
                            String result = "企业号: " + vccId + "  坐席: " + phone;
                            CallConstant.NAME = phone;
                            infoTv.setText(result);
                            applyPermission();
                        });
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void initForm(View view, TaskNumberModel model) {
        nameEdit = view.findViewById(R.id.edit_name);
        sexEdit = view.findViewById(R.id.edit_sex);
        taskNumberEdit = view.findViewById(R.id.edit_task_number);
        statusEdit = view.findViewById(R.id.edit_status);
        purposeEdit = view.findViewById(R.id.edit_purpose);
        remarkEdit = view.findViewById(R.id.edit_remark);
        RelativeLayout callLayout = view.findViewById(R.id.call_relayout);
        RelativeLayout saveLayout = view.findViewById(R.id.save_relayout);
        TextView statusText = view.findViewById(R.id.status_tv);
        Spanned spanned = Html.fromHtml("<font color=\"#FF0000\">" + "*" + "</font>" + "客户状态");
        statusText.setText(spanned);
        taskNumberEdit.setText(model.taskNumber);

        TextView iphoneEdit = view.findViewById(R.id.edit_iphpne);
        TextView reverseEdit = view.findViewById(R.id.edit_reverse);
        TextView batchEdit = view.findViewById(R.id.edit_batch);
        TextView custTypeEdit = view.findViewById(R.id.edit_cust_type_tv);

        if (TextUtils.isEmpty(model.coutomerIPhone)) {
            TextView iphoneText = view.findViewById(R.id.iphone_tv);
            iphoneText.setVisibility(View.GONE);
            iphoneEdit.setVisibility(View.GONE);
        } else {
            iphoneEdit.setText(model.coutomerIPhone);
        }

        if (TextUtils.isEmpty(model.reserve)) {
            TextView reverseText = view.findViewById(R.id.reverse_tv);
            reverseText.setVisibility(View.GONE);
            reverseEdit.setVisibility(View.GONE);
        } else {
            reverseEdit.setText(model.reserve);
        }


        if (TextUtils.isEmpty(model.batchName)) {
            TextView batchText = view.findViewById(R.id.batch_tv);
            batchText.setVisibility(View.GONE);
            batchEdit.setVisibility(View.GONE);
        } else {
            batchEdit.setText(model.batchName);
        }

        if (TextUtils.isEmpty(model.custType)) {
            TextView custTypeText = view.findViewById(R.id.cust_type_tv);
            custTypeText.setVisibility(View.GONE);
            custTypeEdit.setVisibility(View.GONE);
        } else {
            custTypeEdit.setText(model.custType);
        }

        sexEdit.setOnClickListener(this);
        statusEdit.setOnClickListener(this);
        purposeEdit.setOnClickListener(this);
        callLayout.setOnClickListener(this);
        saveLayout.setOnClickListener(this);
    }

    private void showSex() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择性别", CallConstant.sexList,
                        (position, text) -> sexEdit.setText(text))
                .show();
    }

    private void showStatus() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择数据准确性", CallConstant.statusList,
                        (position, text) -> statusEdit.setText(text))
                .show();
    }

    private void showPurpose() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择客户意向", CallConstant.purposeList,
                        (position, text) -> purposeEdit.setText(text))
                .show();
    }

    private void showWarn(View warnImg) {
        String warnStr = TextUtils.isEmpty(CallConstant.currentPhone) ? "没有检测到当前手机号" : "和当前手机号码不匹配";
        new XPopup.Builder(requireActivity())
                .atView(warnImg)
                .hasShadowBg(false) // 去掉半透明背景
                .isViewMode(true)
                .asCustom(new CustomWarnPopup(requireActivity(), warnStr))
                .show();
    }

    private void getPhone() {
        CallConstant.currentPhone = phoneInfoUtils.getNativePhoneNumber(requireActivity());
        Log.e(TAG, "getPhone: " + CallConstant.currentPhone);
        if (!TextUtils.isEmpty(CallConstant.currentPhone)) {
            warnImg.setVisibility(CallConstant.currentPhone.contains(CallConstant.NAME) ? View.GONE : View.VISIBLE);
        }
    }

    private void applyPermission() {
        XXPermissions.with(this).permission(CallConstant.PERMISSION_LIST)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
//                            Toast.makeText(requireActivity(), "请授予权限，否则可能影响使用通话功能", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        getPhone();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
//                        if (doNotAskAgain) {
//                            Toast.makeText(requireActivity(), "被永久拒绝授权，请手动授予对应权限", Toast.LENGTH_SHORT).show();
//                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                            XXPermissions.startPermissionActivity(requireActivity(), permissions);
//                        } else {
//                            System.out.println("授予权限失败");
//                        }
                    }
                });
    }
}

